using System;
using System.IO;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Monkey.Dingtalk.SDK.Attendance;
using Monkey.Dingtalk.SDK.Authentication;
using Monkey.Dingtalk.SDK.Daily;
using Monkey.Dingtalk.SDK.Department;
using Monkey.Dingtalk.SDK.Notice;
using Monkey.Dingtalk.SDK.Report;
using Monkey.Dingtalk.SDK.Staff;
using Monkey.Dingtalk.SDK.Token;
using Monkey.Dingtalk.SDK.User;

namespace ApiTest
{
  public class Startup
  {
    public Startup(IConfiguration configuration) {
      Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services) {
      services.AddControllers().AddNewtonsoftJson();

      services.AddSingleton<IDistributedCache, MemoryDistributedCache>();
      services.AddTransient<TokenApi>();
      services.AddTransient<AttendanceApi>();
      TokenManager.TokenType = TokenType.CORP;
      services.AddSingleton<TokenManager>();
      services.AddTransient<DailyApi>();
      services.AddTransient<DepartmentApi>();
      services.AddTransient<NoticeApi>();
      services.AddTransient<UserApi>();
      services.AddTransient<ReportApi>();
      services.AddTransient<AuthenticationApi>();

      services.AddSwaggerGen(
        options => {
          // 使用反射获取xml文件。并构造出文件的路径
          var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
          var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
          // 启用xml注释. 该方法第二个参数启用控制器的注释，默认为false.
          if (File.Exists(xmlPath)) {
            options.IncludeXmlComments(xmlPath, true);
          }
        }
      );
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();

        app.UseSwagger();
        app.UseSwaggerUI(
          c => {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            c.RoutePrefix = "swagger";
          }
        );
      }

      app.UseHttpsRedirection();

      app.UseRouting();

      app.UseAuthorization();

      app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
    }
  }
}